<?php
namespace Cyfy\Modules\Templates;
/**
 * Module which handles templates of your web page.
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class Module extends \Cyfy\Module
{
    /**
     * Administration interface.
     *
     * @param string
     * @return mixed
     */
	static public function administration($name = '')
	{
        switch($name)
        {
            case "setBlocks":
                return self :: setBlocks();
            case "list":
                return self :: listOf();
            case "":
                return array(
                    "list" => array("name" => self :: t(10), "description" => self :: t(20), "permission" => "change templates"),
                    "setBlocks" => array("name" => self :: t(30), "description" => self :: t(40), "permission" => "set positions of blocks")
                );
		}	
        return false;
	}
	
    /**
     * AJAX callbacks
     * @param string
     */
	static public function ajax($name)
	{
		switch($name)
		{
			case "setBlocks":
				return self :: setBlocksAjax();
            case "reinstall":
				return self :: ajaxReinstall($_POST["template"]);
            case "default":
				return self :: ajaxDefault($_POST["template"]);
		}
        return false;
	}
    
    /**
     * Loades current template on start
     */
    static public function start()
    {
        if(self :: constant("default")){
            \Cyfy\Cyfy ::  $template = self :: constant("default");
        }
        // if we want forced
        if(\Cyfy\Cyfy ::  $query == 'administration/Templates/setBlocks'){
            // force block ids
            \Cyfy\Blocks :: $forcedShow = true;
        }
    }
    /**
     * Changing blocks positions.
     * @return string HTML content
     */
	static private function setBlocks()
	{
		// Javascript and styles
		\Cyfy\Cyfy ::  javaScript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/Templates/setBlocks.js"), "file");
		\Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/Templates/setBlocks.css"), "file");
		\Cyfy\Modules\jQuery\Plugins :: load("jqueryUI");
		
        // current template info 
		$template = self :: parseTemplateXml(\Cyfy\Cyfy ::  $template);
    
		// loads the blocks in this template
		$bts = array();
		$result = \dibi :: query("SELECT [module],[block],[place] FROM [:cyfy:Templates-blocks] WHERE [template] = %s ORDER BY [weight] ASC", \Cyfy\Cyfy ::  $template);
		foreach($result as $bt)
		{
		  $bts[$bt["place"]][] = array("module"=> $bt["module"], "block"=> $bt["block"]); 
		}
		
		// Set blocks
		$output .= "<p><em>" . self :: t(50) . "</em></p>";
		$output .= "<div class=\"form-buttons\"><input type=\"submit\" onclick=\"Template.save();\" value=\"" . self::t(60) . "\" /></div>";
		
		// Load a new block
		$output .= "<h2>" . self :: t(70) . "</h2>";
		$output .= \Cyfy\Blocks :: select("Template.loadBlock(module, block);");
		
		// Loaded Blocks
		$output .= "<h2>" . self :: t(80) . "</h2>";
		$output .= "<div id=\"virtualPlace\"></div>";
        
        // places
		$places = "";
		foreach($template["places"] as $place){
			$places .= "'" . $place . "',";
		}
		$output .= \Cyfy\Cyfy ::  javascript("Template.places = new Array(" . substr($places,0, -1) . ")");
        
        //something posted?
        if($_GET['module'] && $_GET['block']){
            $output .= \Cyfy\Cyfy ::  javascript("Template.loadBlock('{$_GET['module']}', '{$_GET['block']}');");
        }
		 
		 
		return $output;
	}
    
    /**
     * Sets new block positions. Called via AJAX
     * @return bool
     */
	static private function setBlocksAjax()
	{
        if(!\Cyfy\Cyfy ::  permission("Templates", "set positions of blocks"))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
        // is posted
		if(!is_array($_POST["positions"])){
            return false;
        }
		
        // delete old
        \dibi :: query("DELETE FROM [:cyfy:Templates-blocks] WHERE [template] = %s", \Cyfy\Cyfy ::  $template);
         
        foreach($_POST["positions"] as $place => $blocks)
        {
            foreach($blocks as $weight => $b){
                // insert new
                $values = array(
                    'template' => \Cyfy\Cyfy ::  $template,
                    'module' => $b["module"],
                    'block' => $b["block"],
                    'place' => $place,
                    'weight' => $weight
                );
                \dibi :: query("INSERT INTO [:cyfy:Templates-blocks] %v", $values);
            }
        }
        \Cyfy\Message :: set(self :: t(90));
	}
	
    /**
     * Parses info xml.
     *
     * @param string Template name.
     * @return mixed Array of values, if loaded. FALSE otherwise.
     */     
	static private function parseTemplateXml($path)
	{
		$xmlFile = \Cyfy\Cyfy ::  $templatesDir . $path . "/info.xml";
		if(file_exists($xmlFile))
		{
			$template = simplexml_load_file($xmlFile);
			$places = (array) $template -> places;
			return array("path"=> $path, "name"=>(string) $template -> name,"version"=> (string) $template -> version,"description"=>(string) $template -> description,"author"=>(string) $template -> author, "places" => $places["place"]);
		}
		return false;
	}

    /**
     * List of templates.
     * @return string HTML content
     */
    static private  function listOf()
    {
        $directory = scandir(\Cyfy\Cyfy :: $templatesDir);
        array_shift($directory); // removes .
        array_shift($directory); // removes ..
        $templates = array();
    
        // this finds xmls and sends it to parse
        foreach($directory as $path)
        {
            if(file_exists(\Cyfy\Cyfy :: $templatesDir . $path . "/info.xml"))
            {
                $template = self :: parseTemplateXml($path);
                // if valid template
                if($template)
                {
                    $templates[] = $template;        
                }
        
            }
        }
        
        $version = self :: t(100);
        $default = self :: t(110);
        $reinstall = self :: t(120);
        $path = \Cyfy\Cyfy :: getSourcePath(\Cyfy\Cyfy :: $templatesDir);
        
        // going thru the array of templates
        foreach($templates as $template)
        {
            $confirm = self :: t(151, array($template["name"]));
            $checked = (\Cyfy\Cyfy :: $template == $template["path"]) ? " checked = \"checked\"" : "";
            $output .= <<<TEMPLATE
            <h3>{$template["name"]}</h3>
            <img src="{$path}/{$template["path"]}/image.png" alt="{$template["name"]}" />
            <p>{$template["author"]}</p>
            <p><em>{$template["description"]}</em></p>
            <div class="form-buttons">
                <input type="submit"  onclick="Cyfy.ajax('Templates', 'default', '', 'template={$template["path"]}', 'if(confirm(\'{$confirm}\')){Cyfy.redirectTo(\'administration/Templates/setBlocks\'); } else{ Cyfy.refreshPage();}'); return false;" value="{$default}" />
                <input type="submit"  onclick="Cyfy.ajax('Templates', 'reinstall', '', 'template={$template["path"]}'); return false;" value="{$reinstall}" />
            </div>
TEMPLATE;
        }
        return "<div id=\"listOfTemplates\">\n".$output."\n</div>";
    }
    
    /**
     * Reinstalls a template
     * @param string Template name
     */
    static private function ajaxReinstall($template)
    {
        if(!\Cyfy\Cyfy ::  permission("Templates", "set positions of blocks")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        // deletes old
        \dibi :: query("DELETE FROM [:cyfy:Templates-blocks] WHERE [template] = %s", $template);
        
        // insert navigation
        $values = array(
            'template' => $template,
            'module' => 'Menu',
            'block' => 'navigation',
            'place' => 'menu'
        );
        \dibi :: query("INSERT INTO [:cyfy:Templates-blocks] %v", $values);
        
        // insert content
        $values = array(
            'template' => $template,
            'module' => 'Cyfy',
            'block' => 'content',
            'place' => 'content'
        );
        \dibi :: query("INSERT INTO [:cyfy:Templates-blocks] %v", $values);
        \Cyfy\Message :: set(self::t(131, array($template)));
    }
 
    /**
     * Sets default template
     * @param string Template name
     */
    static private function ajaxDefault($template)
    {
        if(!\Cyfy\Cyfy ::  permission("Templates", "change templates")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }

        if(file_exists(\Cyfy\Cyfy ::  $templatesDir . $template))
        {
            // if not used before
            if(\dibi :: query("SELECT count(*) FROM [:cyfy:Templates-blocks] WHERE [template] = %s", $template) -> fetchSingle() == 0)
            {
                // sets the basic blocks - content & menu
                self :: ajaxReinstall($template);
            }
            
            // saves the configuration
            self :: define("default", $template);

            \Cyfy\Message :: set(self :: t(141, array($template)));
            return true;
        }
        return false;
    }
}